import { defineStore } from "pinia";
import { asyncRoute, asyncRouteObj } from "@/router/route";
import { cloneDeep } from "lodash";
import { reqPermission } from "@/api/home";
import route from "@/router";
export const userStore = defineStore({
  id: "app",
  state: (): any => ({
    permissions: [],
    asyncRoutes: [],
    auth: localStorage.getItem("auth"),
  }),
  actions: {
    setLocale(permi: Array<any>) {
      let arr = filterRoutes(cloneDeep(asyncRoute), permi);
      this.asyncRoutes = arr;
      asyncRouteObj.children = arr;
      route.addRoute(asyncRouteObj);
      console.log("权限", arr);
    },
    setAuth(str: string) {
      localStorage.setItem("auth", str);
      this.auth = str;
    },
    async setRoutes() {
      return reqPermission({ auth: this.auth }).then((res: any) => {
        this.setLocale(res.permission);
      });
    },
  },
});
function filterRoutes(routes: any, permi: any) {
  const arr = routes.filter((item: any) => {
    if (item.children && item.children.length) {
      item.children = filterRoutes(item.children, permi);
    }
    return permi.includes(item.permission);
  });
  return arr;
}
